<!-- 参考官方文档 -->
<template>
	<view class="">
		<view class="box-checkbox">
			<checkbox-group @change="onItemChange">
				<view class="box-content" v-for="(item, index) in goods" :key="item.id">
					<checkbox :value="item.id" :checked="item.checked" />
					<text>{{item.name}}</text>
					<text class="box-content-price">{{item.price}}元</text>
					<text class="box-content-delete" @click="onDelete(index)">删除</text>
				</view>
			</checkbox-group>
		</view>
		<view class="box-total">选中{{total}}个产品，总价{{totalPrice}}元</view>
	</view>
</template>

<script lang="ts" setup>
	import { computed, ref } from 'vue';

	let goods = ref([
		{ id: '1', name: '苹果', price: 10, checked: false },
		{ id: '2', name: '橘子', price: 15, checked: false },
		{ id: '3', name: '梨子', price: 20, checked: false }]);
	let selectGroup = ref([]);
	let total = computed(() => selectGroup.value.length);
	let totalPrice = computed(() => goods.value.filter(item => item.checked).reduce((prev, curr) => prev + curr.price, 0));

	//改变勾选
	function onItemChange(e : any) {
		selectGroup.value = e.detail.value;
		goods.value.forEach(item => {
			item.checked = selectGroup.value.includes(item.id);
		});
	};
	//删除
	function onDelete(index : number) {
		let removeGoods = goods.value[index];
		goods.value.splice(index, 1);
		selectGroup.value = selectGroup.value.filter(item => item != removeGoods.id);
	};
</script>

<style lang="scss" scoped>
	.box-checkbox {
		.box-content {
			padding: 10px;

			.box-content-price {
				margin-left: 10px;
			}

			.box-content-delete {
				color: $custom-color-red;
				float: right;
			}
		}
	}

	.box-total {
		padding: 10rpx;
		border-top: 1px solid $custom-color-green;
	}
</style>